package com.neusoft.nepg.gridders.utils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.neusoft.nepg.gridders.utils.AlertUtils.showDialog;

public class FileUtils {
    public static Map mapReader(String filename) {
        try {
            File file = new File(filename);
            if (!file.exists()) showDialog("file not exist!");
            else if(file.length() == 0) return new HashMap<>();
            else {
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    if(ois.readObject() instanceof Map map) return map;
                    else showDialog("the file format is wrong! please check it!");
                    ois.close();
            }
        } catch (Exception e){
            throw new RuntimeException(e);
        }
        return null;
    }

    public static void mapWriter(String filename, Map<String, com.neusoft.nepg.gridders.entity.User> map) {
        try {
            File file = new File(filename);
            if (!file.exists()) showDialog("file not exist!");
            else{
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(map);
                oos.close();
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static List ListReader(String filename) {
        try {
            File file = new File(filename);
            if (!file.exists()) showDialog("file not exist!");
            else{
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    if(ois.readObject() instanceof List list) return list;
                    else showDialog("the file format is wrong! please check it!");
                    ois.close();
            }
        } catch (Exception e){
            throw new RuntimeException(e);
        }
        return null;
    }

    public static List ListWriter(String filename, List list) {
        return null;
    }
}
